package com.qianxun.plugins.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 多realm 认证判断转发，用于区别认证系统存在的多维度角色体系：如管理员、普通用户、web端认证、移动端认证等；
 * @author: huwei
 * @date: 2019/11/28 9:43
 * @version: 1.0.0
 */
public class ModelRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        assertRealmsConfigured();

        LoginTypeToken loginTypeToken = (LoginTypeToken) authenticationToken;
        LoginType loginType = loginTypeToken.getLoginType();


        Collection<Realm> realms = getRealms();
        Collection<Realm> loginRealms = new ArrayList<>();

        //realms选取
        for (Realm realm : realms) {
            if(loginType.getRealmClass().isAssignableFrom(realm.getClass())){
                loginRealms.add(realm);
            }
        }

        if (loginRealms.size() == 1) {
            return doSingleRealmAuthentication(loginRealms.iterator().next(), loginTypeToken);
        } else {
            return doMultiRealmAuthentication(loginRealms, loginTypeToken);
        }
    }
}
